import React from 'react';
import { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import io from 'socket.io-client';

const App = () => {
  const [messages, setMessages] = useState([]);
  const [username, setUsername] = useState('');
  const socketIoConnection = useRef(null);

  useEffect(() => {
    socketIoConnection.current = io('https://xk.heziah.top');
    socketIoConnection.current.on('data_updated', (data) => {
      setMessages(prevMessages => [...prevMessages, data.message]);
    });

    const handleBeforeUnload = () => {
      if (socketIoConnection.current) {
        socketIoConnection.current.disconnect();
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);

      if (socketIoConnection.current) {
        socketIoConnection.current.disconnect();
      }
    }
  }, []);

  useEffect(() => {
    if (username !== '' && socketIoConnection.current) {
      socketIoConnection.current.emit('join', { username });
    }
  }, [username]);

  const checkRoomStatus = async (roomName) => {
    try {
      console.log(`Checking room status for ${roomName}...`);
      const response = await fetch(`https://xk.heziah.top/room_status/${roomName}`);
      const data = await response.json();

      if (data.status === 'active') {
        console.log(`The room ${roomName} is active with ${data.clients} clients.`);
      } else {
        if (username !== '' && socketIoConnection.current) {
          socketIoConnection.current.emit('join', { username });
        }
        console.log(`The room ${roomName} is empty.`);
      }
    } catch (error) {
      console.error('Error fetching room status:', error);
    }
  }

  function sleep(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
  }

  const handleSubmit = async (e) => {
    console.log(e);
    setUsername(e.username);
    sleep(2000);
    checkRoomStatus(e.username)
    try {
      const response = await fetch('https://xk.heziah.top/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(e),
      });

      const data = await response.json();

      if (response.ok) {
        console.log(data.message);
      }
    } catch (error) {
      console.error('发生错误:', error);
    }
  };

  const handleStop = async () => {
    try {
      const response = await fetch('https://xk.heziah.top/stop', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username }), // 添加 username
      });

      const data = await response.json();

      if (response.ok) {
        console.log(data.message);
      } else {
        console.error('提交失败:', data.message);
      }
    } catch (error) {
      console.error('发生错误:', error);
    }
  }
  const logsEndRef = useRef(null);

  useEffect(() => {
    if (logsEndRef.current) {
      logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]);

  return (
    <>
      <div className="mt-10 flex items-center justify-center text-base">
        <div className="bg-white p-8 rounded shadow-md w-4/5 md:w-1/2 space-y-6">
          <h1 className="text-2xl mb-4">选课</h1>
          <Form onFinish={handleSubmit} layout='vertical' className="space-y-4">
            <div>
              <label className='text-xl block mb-2'>mis账号</label>
              <Form.Item name='username' rules={[{ required: true, message: '请输入mis账号' }]}>
                <Input />
              </Form.Item>
            </div>
            <div>
              <label className='text-xl block mb-2'>mis密码</label>
              <Form.Item name='password' rules={[{ required: true, message: '请输入mis密码' }]}>
                <Input.Password />
              </Form.Item>
            </div>
            <div>
              <label className='text-xl block mb-2'>课程：</label>
              <p className='text-sm mb-2'>一个格内请填写一门课程</p>
              <Form.List name="course" initialValue={['']}>
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space key={key} className='flex' align="baseline">
                        <Form.Item {...restField} name={name} rules={[{ required: true, message: '请输入课程名称' }]} className='w-full'>
                          <Input placeholder="例如：网球07或网球" />
                        </Form.Item>
                        <MinusCircleOutlined onClick={() => { remove(name) }} />
                      </Space>
                    ))}
                    <Form.Item>
                      <Button type="dashed" onClick={() => { add() }} icon={<PlusOutlined />}>
                        添加课程
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </div>
            <Form.Item className="space-x-4">
              <Button type="primary" className='bg-blue-500 hover:bg-blue-600' htmlType="submit">
                提交
              </Button>
              <Button type="primary" danger className='hover:bg-red-500 active:bg-red-600' onClick={handleStop}>
                停止
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>

      <div className="mt-10 flex items-center justify-center">
        <div className="bg-gray-100 p-6 rounded-xl shadow-lg w-4/5 md:w-1/2 h-60 overflow-y-auto border-2 border-gray-700">
          <div className="space-y-1">
            {messages
              .filter(log => {
                const pattern = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/g;
                const logWithoutTime = log.replace(pattern, '').trim();
                return logWithoutTime !== "";
              })
              .map((log, index) => (
                <div key={index} className="flex items-center space-x-2 border-b text-sm border-gray-600">
                  <span className="text-gray-500 font-mono">{index + 1}</span>
                  <span className="border-l border-gray-600 px-2 font-mono">{log}</span>
                </div>
              ))}
            <div ref={logsEndRef} />
          </div>
        </div>
      </div>


    </>
  );
};

export default App;
